package org.zhb.sql.query.sys.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhb.sql.query.model.User;
import org.zhb.sql.query.sys.repository.UserRepository;
import org.zhb.sql.query.sys.service.UserService;

import com.mysema.query.types.Predicate;
import static org.zhb.sql.query.model.QUser.user;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserRepository userRepository;

	@Override
	@Transactional
	public User findById(String id) {
		return userRepository.findOne(id);
	}

	@Override
	@Transactional
	public List<User> findAll(User model) {
		Predicate predicate = (Predicate) user.realName.equalsIgnoreCase(model.getRealName())
				.and(user.realName.startsWithIgnoreCase(model.getRealName()));
		return (List<User>) userRepository.findAll(predicate);
	}

	@Override
	@Transactional
	public void save(User model) {
		userRepository.save(model);
	}

	@Override
	@Transactional
	public User findByUserNameAndPassword(String userName, String password) {
		Predicate predicate = (Predicate) user.userName.eq(userName).and(user.password.eq(password));
		return userRepository.findOne(predicate);
	}

	@Override
	@Transactional
	public void delete(String id) {
		userRepository.delete(id);
	}

	@Override
	@Transactional
	public User selectByUserName(String userName) {
		Predicate predicate = (Predicate) user.userName.eq(userName);
		return userRepository.findOne(predicate);
	}

	@Override
	@Transactional
	public User findByPhone(String phone) {
		Predicate predicate = (Predicate) user.phone.eq(phone);
		return userRepository.findOne(predicate);
	}

	@Override
	@Transactional
	public User findByEmail(String email) {
		Predicate predicate = (Predicate) user.email.eq(email);
		return userRepository.findOne(predicate);
	}

	@Override
	@Transactional
	public void updatePasswordByUserName(String password, String userName) {
		userRepository.updatePasswordByUserName(password, userName);
	}

	@Override
	@Transactional
	public void update(User model) {
		userRepository.saveAndFlush(model);
	}

	/**
	 * 带有条件的分页查询
	 */
	@Override
	@Transactional
	public Page<User> selectModelByCondition(PageRequest pageRequest) {
		// Predicate predicate = (Predicate) user.email.eq("");
		return userRepository.findAll(null, pageRequest);
	}

}
